<template>
  <div class="gl_contentBox gl_heightFull">
    <p class="header">首页内容</p>
    <el-row class="content_top">
      <el-col v-if="!loading" :span="14">
        <el-form ref="indexForm" class="gl_form_mini" :model="indexForm" :rules="IndexForm_rules" label-width="110px">
          <el-row>
            <el-col :span="12" align="right">
              <el-form-item label="道馆名称" prop="name">
                <el-input v-model="indexForm.name" :disabled="checkIsUsePlatForm(indexForm.name, paltFormData.name)" placeholder="请输入" type="text" size="mini" />
                <el-checkbox :value="checkIsUsePlatForm(indexForm.name, paltFormData.name)" :disabled="!paltFormData.name" @change="isUsePlatFormData($event, 'name', 'name')">使用平台数据</el-checkbox>
              </el-form-item>
              <el-form-item label="联系人" prop="linkman">
                <el-input v-model="indexForm.linkman" :disabled="checkIsUsePlatForm(indexForm.linkman, paltFormData.contactPerson)" placeholder="请输入" type="text" size="mini" />
                <el-checkbox :value="checkIsUsePlatForm(indexForm.linkman, paltFormData.contactPerson)" :disabled="!paltFormData.contactPerson" @change="isUsePlatFormData($event, 'linkman', 'contactPerson')">使用平台数据</el-checkbox>
              </el-form-item>
              <el-form-item label="联系电话" prop="linkPhoneNumber">
                <el-input v-model="indexForm.linkPhoneNumber" :disabled="checkIsUsePlatForm(indexForm.linkPhoneNumber, paltFormData.phoneNumber)" placeholder="请输入" type="text" size="mini" />
                <el-checkbox :value="checkIsUsePlatForm(indexForm.linkPhoneNumber, paltFormData.phoneNumber)" :disabled="!paltFormData.phoneNumber" @change="isUsePlatFormData($event, 'linkPhoneNumber', 'phoneNumber')">使用平台数据</el-checkbox>
              </el-form-item>
              <el-form-item label="教练人数" prop="coachNumber">
                <el-input v-model="indexForm.coachNumber" :disabled="checkIsUsePlatForm(indexForm.coachNumber, paltFormData.coachNum)" placeholder="请输入" type="text" size="mini" />
                <el-checkbox :value="checkIsUsePlatForm(indexForm.coachNumber, paltFormData.coachNum)" :disabled="!paltFormData.coachNum" @change="isUsePlatFormData($event, 'coachNumber', 'coachNum')">使用平台数据</el-checkbox>
              </el-form-item>
              <el-form-item label="学员人数" prop="studentNumber">
                <el-input v-model="indexForm.studentNumber" :disabled="checkIsUsePlatForm(indexForm.studentNumber, paltFormData.studentNum)" placeholder="请输入" type="text" size="mini" />
                <el-checkbox :value="checkIsUsePlatForm(indexForm.studentNumber, paltFormData.studentNum)" :disabled="!paltFormData.studentNum" @change="isUsePlatFormData($event, 'studentNumber', 'studentNum')">使用平台数据</el-checkbox>
              </el-form-item>
              <el-form-item label="首页内容标题" prop="title">
                <el-input v-model="indexForm.title" placeholder="请输入首页内容标题  " type="text" size="mini" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col align="right">
                  <el-form-item label="详细地址" prop="parentTAProvinceCode">
                    <el-cascader
                      v-model="area"
                      clearable
                      size="mini"
                      :disabled="checkIsUsePlatForm(indexForm.address, paltFormData.address)"
                      :options="cache.district"
                      :props="{ value: 'code', label: 'name' }"
                      placeholder="请选择省市区"
                      style="width: 100%;"
                      @change="changeArea"
                    />
                  </el-form-item>
                  <el-form-item label="" prop="address">
                    <el-input v-model="indexForm.address" :disabled="checkIsUsePlatForm(indexForm.address, paltFormData.address)" placeholder="请输入" type="textarea" :rows="2" size="mini" />
                    <el-checkbox :value="checkIsUsePlatForm(indexForm.address, paltFormData.address)" :disabled="!paltFormData.address" @change="isUsePlatFormData($event, 'address', 'address')">使用平台数据</el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item label="上传图片" prop="imagePath">
                  <el-input v-show="false" v-model.trim="indexForm.imagePath" />
                  <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
                    <photo-cropper ref="photoCropper" :photograph="false" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
                  </el-dialog>
                  <div class="upload_game_img" :class="indexForm.imagePath ? '' : 'no_pointer'" @click="openPhotoCropper">
                    <img v-if="indexForm.imagePath" class="show_img" :src="getStaticFileUrl(indexForm.imagePath)">
                    <i v-else class="el-icon-plus" />
                  </div>
                  <el-checkbox :value="checkIsUsePlatForm(indexForm.imagePath, paltFormData.imagePath)" :disabled="!paltFormData.imagePath" @change="isUsePlatFormData($event, 'imagePath', 'imagePath')">使用平台数据</el-checkbox>
                </el-form-item>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div>
                <el-form-item label="描述" prop="content" style="width:100%">
                  <Tinymce v-model="indexForm.content" :height="300" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div class="form_btn">
          <!-- 取消按钮 -->
          <el-button @click="init">{{ $t('button.cancel') }}</el-button>
          <el-button type="default" :loading="btnLoading" @click="preview()">预览</el-button>
          <!-- 编辑的保存按钮 -->
          <el-button type="primary" :loading="btnLoading" @click="confrimForm()">确定</el-button>
        </div>
      </el-col>
      <!-- <el-col :span="8"></el-col> -->
    </el-row>

    <el-dialog
      class="gl_dialog_TitleLine"
      width="420px"
      title="预览"
      :append-to-body="true"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <moblePreview :preview-data="indexForm" />
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import photoCropper from '@/components/PhotoCropper';
import Tinymce from '@/components/Tinymce';
import moblePreview from './mobilePreview.vue';
import { api_GET_EventsManagementDelegationId } from '@/extend/api/gameswaggerApi/app.js';
import {
  api_GET_ClubClubIndexClubMemberCount, // 获取道馆学生教练的数量
  api_GET_ClubClubIndexClubIndex, // 获取道馆首页
  api_POST_ClubClubIndex, // 创建道馆首页
  api_PUT_ClubClubIndex // 修改道馆首页
} from '@/extend/api/hallswaggerApi/app.js';
import { CreateClubIndexInput } from '@/lib/form/hall/swaggerForm.js';
import { IndexForm_rules } from '@/lib/validate/mobileConfig/index.js';
export default {
  components: {
    photoCropper,
    Tinymce,
    moblePreview
  },
  data () {
    return {
      loading: false,
      isUpdate: false, // 是更新还是创建
      paltFormData: {}, // 当前机构信息
      indexForm: new CreateClubIndexInput(),
      IndexForm_rules: new IndexForm_rules(),
      file: '',
      area: [], // 配送区域
      btnLoading: false,
      dialogVisible: false,
      // 上传照片
      photoCropperVisible: false, // 上传图片窗口的显示与隐藏
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      photoCropperOption: {
        img: '',
        autoCropWidth: '310px',
        autoCropHeight: '160px',
        enlarge: 1,
        fixedNumber: [310, 160]
      }
    };
  },
  computed: {
    ...mapState({
      cache: state => state.dict.cache,
      UserType: state => state.user.currentUserType
    })
  },
  created() {
    this.getDictByType(['district']);
    this.init();
  },
  methods: {
    ...mapActions({ getDictByType: 'dict/getDictByType' }),
    init() {
      this.loading = true;
      this.indexForm = new CreateClubIndexInput();
      this.getCurrClubIndex();
      Promise.all([this.getDelegationInfo(), this.getPlatFormMemberData()]).then(
        res => {
          this.paltFormData = {
            ...res[0],
            ...res[1]
          };
          this.loading = false;
          console.log('res', this.paltFormData);
        }
      ).catch(error => {
        this.loading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 获取当前道馆配置
    getCurrClubIndex() {
      this.loading = true;
      api_GET_ClubClubIndexClubIndex().then(
        res => {
          this.loading = false;
          if (res) {
            this.isUpdate = true;
            this.indexForm = res;
            this.area = [this.indexForm['parentTAProvinceCode'], this.indexForm['parentTACityCode'], this.indexForm['parentTACountyCode']];
          } else {
            this.isUpdate = false;
            this.indexForm = new CreateClubIndexInput();
          }
        }
      ).catch(error => {
        this.loading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 修改省市区
    changeArea(val) {
      this.indexForm.parentTAProvinceCode = val[0];
      this.indexForm.parentTACityCode = val[1];
      this.indexForm.parentTACountyCode = val[2];
      this.$refs.indexForm.validateField('parentTAProvinceCode');
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper() {
      if (this.indexForm['imagePath']) {
        this.$set(this.photoCropperOption, 'img', this.getStaticFileUrl(this.indexForm['imagePath']));
      }
      this.photoCropperVisible = true;
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$set(this.indexForm, 'imagePath', res.tempUrl);
        this.photoCropperVisible = false;
      });
    },
    isUsePlatFormData(flag, settingCode, platFormCode) {
      console.log('val', settingCode, platFormCode);
      if (flag) {
        // 使用平台数据
        // 先将原始数据保存再赋值，方便还原
        this.indexForm['old_' + settingCode] = this.indexForm[platFormCode];
        this.indexForm[settingCode] = this.paltFormData[platFormCode];
        if (settingCode === 'address') {
          this.indexForm['old_parentTAProvinceCode'] = this.indexForm['parentTAProvinceCode'];
          this.indexForm['old_parentTACityCode'] = this.indexForm['parentTACityCode'];
          this.indexForm['old_parentTACountyCode'] = this.indexForm['parentTACountyCode'];
          this.indexForm['parentTAProvinceCode'] = this.paltFormData['provinceCode'];
          this.indexForm['parentTACityCode'] = this.paltFormData['cityCode'];
          this.indexForm['parentTACountyCode'] = this.paltFormData['countyCode'];
          this.area = [this.indexForm['parentTAProvinceCode'], this.indexForm['parentTACityCode'], this.indexForm['parentTACountyCode']];
        }
      } else {
        // 不使用原始数据，清空
        if (settingCode === 'address') {
          this.area = [];
          this.indexForm['parentTAProvinceCode'] = null;
          this.indexForm['parentTACityCode'] = null;
          this.indexForm['parentTACountyCode'] = null;
        }
        this.indexForm[settingCode] = null;
      }
      console.log('选中之后', this.indexForm);
    },
    checkIsUsePlatForm(settingVal, platFormVal) {
      if (settingVal === platFormVal) {
        if (settingVal === 'address') {
          if (this.indexForm['parentTAProvinceCode'] === this.paltFormData['provinceCode'] &&
          this.indexForm['parentTACityCode'] === this.paltFormData['cityCode'] &&
          this.indexForm['parentTACountyCode'] === this.paltFormData['countyCode'] &&
          this.indexForm.address === this.paltFormData.address) {
            return true;
          } else {
            return false;
          }
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    // 预览
    preview() {
      this.dialogVisible = true;
    },
    // 确定
    confrimForm() {
      this.btnLoading = true;
      this.$refs['indexForm'].validate((valid) => {
        if (valid) {
          if (this.isUpdate) {
            this.updateClubIndex();
          } else {
            this.createClubIndex();
          }
        } else {
          this.btnLoading = false;
        }
      });
    },
    // 创建
    createClubIndex() {
      this.indexForm.studentNumber = this.indexForm.studentNumber ? this.indexForm.studentNumber : null;
      this.indexForm.coachNumber = this.indexForm.coachNumber ? this.indexForm.coachNumber : null;
      api_POST_ClubClubIndex(this.indexForm).then(res => {
        this.$message({
          type: 'success',
          message: '上传成功'
        });
        this.btnLoading = false;
        this.getCurrClubIndex();
      }).catch(error => {
        this.btnLoading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 更新
    updateClubIndex() {
      this.indexForm.studentNumber = this.indexForm.studentNumber ? this.indexForm.studentNumber : null;
      this.indexForm.coachNumber = this.indexForm.coachNumber ? this.indexForm.coachNumber : null;
      api_PUT_ClubClubIndex(this.indexForm).then(res => {
        this.$message({
          type: 'success',
          message: '更新成功'
        });
        this.btnLoading = false;
        this.getCurrClubIndex();
      }).catch(error => {
        this.btnLoading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 获取机构信息
    getDelegationInfo() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementDelegationId(this.UserType.delegationId).then(res => {
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 获取平台学生教练数量
    getPlatFormMemberData() {
      return new Promise((resolve, reject) => {
        api_GET_ClubClubIndexClubMemberCount().then(res => {
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 上传图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
.header {
  padding-bottom: 20px;
  text-align: left;
  border-bottom: 1px solid #DCDFE6;
}
.content_top {
  margin: 20px 0;
}
.form_btn {
  text-align: center;
}
.upload_game_img.no_pointer {
  cursor: default;
}
.upload_game_img {
  width: 310px;
  height: 166px;
  line-height: 205px;
  text-align: center;
  font-size: 20px;
  border: 1px dotted #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  // margin: 10px 0;
}
.upload_game_img .show_img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 6px;
  // vertical-align: middle;
}
</style>
